if(!window.xflib || !window.xflib.client) window.xflib = { client: {} }

xflib.client.ProductUi = class ProductUi {

    constructor(productService){
        this.productService = productService;
        this.products = new Map();
        this.productModal = new xflib.client.ProductModal();
        this.productSelect = document.getElementById('product-select');

        document.getElementById('productAddbtn').addEventListener('click', this.addProductHandler.bind(this));
        document.getElementById('productEditbtn').addEventListener('click', this.editProductHandler.bind(this));
        document.getElementById('productDeleteBtn').addEventListener('click', this.deleteProductHandler.bind(this));    

    }

    // 添加产品处理
    async addProductHandler(){
        // 打开编辑产品模态框
        this.productModal.openModal('add', (productCode, productName, tag)=>this.saveProduct(productCode, productName, tag));
    }

    // 编辑产品处理
    async editProductHandler(){
        // 獲取dangqian当前选中的产品项
        const productCode = this.productSelect.options[this.productSelect.selectedIndex].value;
        const productName = this.productSelect.options[this.productSelect.selectedIndex].data;
        
        // 如果当前选中的产品项为全部，则提示用户选择需要编辑的产品
        if(productCode === 'all'){
            alert('请选择需要编辑的产品');
            return;
        }

        // 打开编辑产品模态框
        this.productModal.openModal('edit', (productCode, productName, tag)=>this.saveProduct(productCode, productName,tag), productCode, productName); 

    }

    // 删除产品处理
    async deleteProductHandler(){
        this.deleteProduct();
    }

    // 保存产品到存储
    async saveProduct(productCode, productName, tag){
        const _this=this;
        return new Promise((resolve, reject)=>{
            // 检查产品代码是否重复
            if ([..._this.products.keys()].includes(productCode) && _this.products.get(productCode) === productName) {
                alert('产品名称不能重复');
                reject(false);
            }

            try{ // 保存产品
                _this.products.set(productCode, productName);
                // _this.refreshProductSelect();
                if(tag === 'add'){
                    _this.productService.create(productCode, productName).then(response=>{
                        if(response.success){
                            _this.refreshProductSelect(productCode);
                        }
                    });
                } else if(tag === 'edit'){
                    const oldValue = this.productSelect.options[this.productSelect.selectedIndex].value;
                    _this.productService.update(oldValue, productCode, productName).then(response=>{
                        if(response.success){
                            _this.refreshProductSelect(productCode);
                        }
                    });
                }

                resolve(true);
            }catch(e){
                reject(false);
            }
        });
    }

    // 从存储删除产品
    async deleteProduct() {
        const selectedProduct = this.productSelect.value;
        if (selectedProduct === 'all') {
            alert('请选择要删除的产品');
            return;
        }

        const projectService = window.xflib.client.Application.getBean('projectService');
        const projects = await projectService.queryByProductCode(selectedProduct);
        if (projects &&Object.entries(projects).length > 0) {
            alert(`产品 "${this.productSelect.options[this.productSelect.selectedIndex].data}" 已被使用，不能删除!`);
            return;
        }

        if (!confirm(`确定要删除产品 "${this.productSelect.options[this.productSelect.selectedIndex].data}" 吗？`)) {
            return;
        }

        const _this=this;
        _this.products.delete(selectedProduct);
        _this.productService.delete(selectedProduct).then(response=>{
            if(response.success){
                _this.refreshProductSelect();
            }
        });

    }

    // 更新产品选择框, 自动选择 value 指定的产品
    async refreshProductSelect(value = 'all') {
        this.productService.queryByProductCodes().then(response=>{
            if(response){
                this.products = new Map(Object.entries(response));
                this.productSelect.innerHTML = '<option value="all">全部</option>';
                this.products.forEach((name, code) => {
                    const option = document.createElement('option');
                    option.value = code;
                    option.data = name;
                    option.textContent = code + ' - ' + name;
                    this.productSelect.appendChild(option);
                    this.productSelect.value = value;
                });
                xflib.client.ProjectModal.productCodeSelect().innerHTML = this.productSelect.innerHTML;
            }
        });
        this.productSelect.value = value;
    }

}

